
function startTimer() {
    let total = Number.parseInt(document.getElementById('timeoutSeconds').textContent);
    console.log(`Start timer with: ${total}`);

    let timer = setInterval(() => {
        let date = new Date(null);
        date.setSeconds(total);
        let remain = date.toISOString().substr(11, 8);

        total--;

        if (total < 0) {
            clearInterval(timer);
            console.log('navigate to timeout page');
            window.open(`request-timeout?id=${getId()}`, '_self');
            return;
        }
        
        document.getElementById('remain').innerText = remain;
    }, 1000);
}

function getId() {
    return document.getElementById('requestId').textContent;
}

function ready() {
    document.getElementById('btn-grant').onclick = (ev) => {

        let id = getId();
        post('/api/requests/grant',
            { grant: true, id: id },
            (data) => {
                console.log('grant result ', data);
                if (data.message) {
                    window.open('500', '_self');
                } else {
                    window.open(`request-granted?id=${id}`, '_self');
                }
            });
    }

    document.getElementById('btn-reject').onclick = (ev) => {

        let id = getId();
        post('/api/requests/grant',
            { grant: false, id: id },
            (data) => {
                console.log('grant result ', data);
                if (data.message) {
                    window.open('500', '_self');
                } else {
                    window.open(`request-rejected?id=${id}`, '_self');
                }
            });
    }

    startTimer();
}

$(ready);